package org.example.handler;

import com.alibaba.fastjson.JSONObject;
import org.example.common.enums.ResultEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

public class MyAuthExceptionEntryPoint implements AuthenticationEntryPoint {

    private static final Logger logger = LoggerFactory.getLogger(MyAuthExceptionEntryPoint.class);

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        logger.error("MyAuthExceptionEntryPoint:{}",authException.getMessage());

        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.ordinal());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);

        HashMap<String, Object> resMap = new HashMap<>();
        resMap.put("code", ResultEnum.InvalidTokenResult.getCode());
        resMap.put("msg",ResultEnum.InvalidTokenResult.getMsg());

        response.getWriter().write(JSONObject.toJSONString(resMap));
        response.flushBuffer();

    }


}
